from scipy import *
from numpy import power
from simu_common import Cbid, getPt, getRevenue, getStepRevenue
import simu_rng2 as simu_rng

g_threshold = 0.0
g_arrival_rate = 5

def bids_key(bid):
    return bid.r
    
def get_bids(vp, vs):
    bids = []
    length = len(vp)
    for i in xrange(0, length):
        bids.append(Cbid(vp[i], vs[i]))
        
    return bids
    
def getThreshold(bids, l):
    '''
        assuming that the bids are sorted in order by p*s
        take the lth highest as threshold
    '''
    length = len(bids)
    if l < length:
        return bids[l].r
    else:
        return 0.0;
     
def exp_Rrate1(k=10, T=50, l=0, tao=1.4):

    bids = []
    threshold = 0
    total_revenue = 0.0
    is_modified = False
    
    arrivals = simu_rng.get_poisson(g_arrival_rate, T)
    total = sum(arrivals)
    vp = simu_rng.get_uniform(total)
    vs = simu_rng.get_uniform(total)
    c_bids = get_bids(vp, vs)

    for a in arrivals:
        is_modified = False
        for i in xrange(0, a):
            bid = c_bids.pop(0) 
            if bid.r > threshold:
                bids.append(bid)
                is_modified = True

        if is_modified:
            bids.sort(key=bids_key, reverse=True)

        if not(threshold > 0):
            threshold = getThreshold(bids, l) # Once the kth order statistic is get, keep it

        total_revenue = total_revenue + getStepRevenue(bids, k, tao)
        
    print threshold
    return total_revenue/T
    
def sample1(k=8):
    for i in xrange(0, k+5):
        r = 0.0
        t = 100
        for j in xrange(0, t):
            r = r + exp_Rrate1(k=k, l=i)
        print i, r/t

if __name__ == "__main__":
    sample1()            
